import React, { useState, useEffect, useRef } from "react";
import {
  PageHeader,
  Steps,
  Button,
  Form,
  Input,
  Select,
  message,
  notification,
} from "antd";
import { useParams } from "react-router";
import { useNavigate } from "react-router";
import axios from "axios";
import NewsEditor from "../../../components/newsEditor";

export default function NewsUpdate() {
  const { Step } = Steps;
  const [current, setCurrent] = useState(0);
  const [categories, setCategories] = useState([]);
  const { Option } = Select;
  const NewsForm = useRef(null);
  const navigate = useNavigate();
  const params = useParams();
  // 存三页的新闻信息
  const [formInfo, setFormInfo] = useState({});
  const [contentInfo, setContentInfo] = useState("");
  // const [formInfo, setFormInfo] = useState(initialState);
  useEffect(() => {
    axios.get("http://localhost:5000/categories").then((res) => {
      setCategories(res.data);
    });
  }, []);
  // const user = JSON.parse(localStorage.getItem("token"));
  useEffect(() => {
    // console.log(params.id);
    axios
      .get(
        `http://localhost:5000/news/${params.id}?_expand=category&_expand=role`
      )
      .then((res) => {
        // console.log(res.data);
        // console.log(NewsForm);
        // 初始化表单的值
        const { title, categoryId, contentInfo } = res.data;
        NewsForm.current.setFieldsValue({ title, categoryId });
        setContentInfo(contentInfo);
      })
      .catch(() => {
        message.warning("获取新闻信息失败！");
      });
  }, [params.id]);
  const handelNext = () => {
    // console.log(NewsForm);
    // 基本信息页
    if (current === 0) {
      NewsForm.current
        .validateFields()
        .then((res) => {
          // console.log(res);
          setFormInfo(res);
          setCurrent(current + 1);
        })
        .catch(() => {
          message.warning("请输入正确的基本信息！");
        });
    } else {
      if (contentInfo === "" || contentInfo.trim() === "<p></p>") {
        // 新闻内容为空，不能放行
        message.warning("新闻内容禁止为空");
      } else {
        // 不为空 则跳转到下一页
        setCurrent(current + 1);
      }
    }
    // setCurrent(current + 1);
  };
  const handelPre = () => {
    setCurrent(current - 1);
  };

  // 保存草稿箱
  const handleSave = (auditState) => {
    axios
      .patch(`http://localhost:5000/news/${params.id}`, {
        ...formInfo,
        contentInfo,
        auditState,
      })
      .then(() => {
        navigate(
          auditState === 0 ? "/news-manage/draft" : "/audit-manage/list"
        );
        // 成功后的消息通知
        notification.open({
          message: "Notification Title",
          description:
            auditState === 0
              ? " 您可以到草稿箱中查看编辑后的新闻"
              : "您可以到审核列表中查看编辑后的新闻",
          duration: 5,
          placement: "bottomRight",
        });
      });
  };
  return (
    <div>
      <PageHeader title="编辑新闻" onBack={() => navigate(-1)} />
      <Steps current={current}>
        <Step title="基本信息" description="新闻标题, 新闻分类" />
        <Step title="新闻内容" description="新闻主题内容" />
        <Step title="新闻提交" description="保存草稿或者提交审核" />
      </Steps>

      <div style={{ marginTop: "50px" }}>
        {/* 新闻基本信息 */}
        <div style={{ display: current === 0 ? "" : "none" }}>
          <Form
            ref={NewsForm}
            name="basic"
            labelCol={{ span: 2 }}
            wrapperCol={{ span: 22 }}
            // initialValues={{ remember: true }}
            // onFinish={onFinish}
            // onFinishFailed={onFinishFailed}
            autoComplete="off"
          >
            <Form.Item
              label="新闻标题"
              name="title"
              rules={[{ required: true, message: "请输入新闻标题" }]}
            >
              <Input />
            </Form.Item>

            <Form.Item
              label="新闻分类"
              name="categoryId"
              rules={[{ required: true, message: "请选择新闻种类" }]}
            >
              <Select>
                {categories.map((category) => {
                  return (
                    <Option value={category.id} key={category.id}>
                      {category.title}
                    </Option>
                  );
                })}
              </Select>
            </Form.Item>
          </Form>
        </div>
        {/* 新闻内容 */}
        <div style={{ display: current === 1 ? "" : "none" }}>
          {/* 子传父 父组件要接受子组件的富文本内容 */}
          {/* value可接收到传过来的信息 */}
          <NewsEditor
            getContent={(value) => {
              // console.log(value);
              setContentInfo(value);
            }}
            contentInfo={contentInfo}
          ></NewsEditor>
        </div>
        {/*  */}
        <div style={{ display: current === 2 ? "" : "none" }}>333</div>
      </div>

      <div style={{ marginTop: "20px" }}>
        <Button
          type={current > 0 ? "primary" : ""}
          disabled={current < 1}
          onClick={() => handelPre()}
        >
          上一步
        </Button>
        &nbsp;
        {current === 2 ? (
          <Button type="danger" onClick={() => handleSave(0)}>
            保存草稿箱
          </Button>
        ) : (
          ""
        )}{" "}
        &nbsp;
        {current === 2 ? (
          <Button type="danger" onClick={() => handleSave(1)}>
            提交审核
          </Button>
        ) : (
          ""
        )}
        &nbsp;
        <Button
          type={current < 2 ? "primary" : ""}
          disabled={current > 1}
          onClick={() => handelNext()}
        >
          下一步
        </Button>
      </div>
    </div>
  );
}
